package com.liu.webstore.controller;

import com.alibaba.fastjson.JSONObject;
import com.liu.webstore.common.Constant;
import com.liu.webstore.entity.Message;
import com.liu.webstore.entity.Page;
import com.liu.webstore.entity.User;
import com.liu.webstore.service.MessageService;
import com.liu.webstore.service.UserService;
import com.liu.webstore.util.HostHolder;
import com.liu.webstore.util.WebstoreUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

/**
 * @Author LiuYumei
 * @Date 2022/7/28 23:01
 */
@Controller
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @GetMapping("/letter/list")
    public String getLetterList(Model model, Page page) {
        int userId = hostHolder.getUser().getId();
        // 分页信息
        page.setLimit(5);
        page.setPath("/message/letter/list");
        page.setRows(messageService.selectConversationCount(userId));
        // 会话列表
        List<Message> conversationList = messageService.selectConversations(
                userId, page.getOffert(), page.getLimit());
        List<Map<String, Object>> conversations = new ArrayList<>();
        if (Objects.nonNull(conversationList)) {
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);
                // 两用户之间会话的数量
                map.put("letterCount", messageService.selectLetterCount(message.getConversationId()));
                // 用户会话消息未读数量
                map.put("unreadCount", messageService.selectLetterUnreadCount(message.getConversationId(), userId));
                // 目标ID
                int targetId = userId == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.getUserById(targetId));
                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);
        // 查询用户总未读消息数量
        int letterUnreadCount = messageService.selectLetterUnreadCount(null, userId);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        // 查询消息通知未读消息数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(userId, null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);
        return "/site/letter";
    }

    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable String conversationId, Model model, Page page) {

        // 分页信息
        page.setLimit(5);
        page.setPath("/message/letter/detail/" + conversationId);
        page.setRows(messageService.selectLetterCount(conversationId));
        List<Message> letterList = messageService.selectLetters(conversationId, page.getOffert(), page.getLimit());
        List<Map<String, Object>> letters = new ArrayList<>();
        if (Objects.nonNull(letterList)) {
            for (Message letter : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", letter);
                map.put("fromUser", userService.getUserById(letter.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);
        // 私信目标
        model.addAttribute("target", getLetterTarget(conversationId));
        // 设为已读
        List<Integer> ids = getLetterIds(letterList);
        if (!CollectionUtils.isEmpty(ids)) {
            messageService.readMessage(ids);
        }

        return "/site/letter-detail";
    }

    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int u0 = Integer.parseInt(ids[0]);
        int u1 = Integer.parseInt(ids[1]);
        if (hostHolder.getUser().getId() == u0) {
            return userService.getUserById(u1);
        } else {
            return userService.getUserById(u0);
        }
    }

    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> list = new ArrayList<>();
        if (Objects.nonNull(letterList)) {
            for (Message message : letterList) {
                if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
                    list.add(message.getId());
                }
            }
        }
        return list;
    }

    @GetMapping("/letter/notice")
    public String getSystemNotice(Model model, Page page) {
        int userId = hostHolder.getUser().getId();
        page.setLimit(5);
        page.setPath("/message/letter/notice");
        page.setRows(messageService.selectSystemNoticeCount(userId));
        List<Message> systemNoticeList = messageService.selectSystemNoticeList(userId, page.getOffert(), page.getLimit());
        List<Map<String, Object>> notices = new ArrayList<>();
        if (Objects.nonNull(systemNoticeList)) {
            for (Message systemNotice : systemNoticeList) {
                Map<String, Object> map = new HashMap<>();
                map.put("systemNotice", systemNotice);
                //map.put("systemNoticeCount", messageService.selectSystemNoticeCount(userId));
                notices.add(map);
            }
        }
        model.addAttribute("notices", notices);
        model.addAttribute("systemNoticeCount", messageService.selectSystemNoticeCount(userId));
        return "/site/notice";
    }

    /**
     * 异步方法，发送私信
     */
    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String toName, String content) {
        User target = userService.findByName(toName);
        if (Objects.isNull(target)) {
            return WebstoreUtil.getJsonString(404, "目标用户不存在！");
        }
        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.saveMessage(message);
        return WebstoreUtil.getJsonString(200);
    }

    @PostMapping("/letter/delete/{letterDetailId}")
    @ResponseBody
    public String deleteLetterDetial(@PathVariable("letterDetailId") int letterDetailId) {
        messageService.removeLetterDetial(letterDetailId);
        return WebstoreUtil.getJsonString(200);
    }

    @GetMapping("/notice/list")
    public String getNoticeList(Model model) {
        int userId = hostHolder.getUser().getId();
        // 查询评论通知
        Message message = messageService.findLatestNotice(userId, Constant.TOPIC_COMMENT);
        if (Objects.nonNull(message)) {
            Map<String, Object> messageVo = new HashMap<>();
            getMessageVo(userId, message, messageVo, Constant.TOPIC_COMMENT);
            model.addAttribute("commentNotice", messageVo);
        }

        // 查询点赞通知
        message = messageService.findLatestNotice(userId, Constant.TOPIC_LIKE);
        if (Objects.nonNull(message)) {
            Map<String, Object> messageVo = new HashMap<>();
            getMessageVo(userId, message, messageVo, Constant.TOPIC_LIKE);
            model.addAttribute("likeNotice", messageVo);
        }

        // 查询关注通知
        message = messageService.findLatestNotice(userId, Constant.TOPIC_FOLLOW);
        if (Objects.nonNull(message)) {
            Map<String, Object> messageVo = new HashMap<>();
            getMessageVo(userId, message, messageVo, Constant.TOPIC_FOLLOW);
            model.addAttribute("followNotice", messageVo);
        }

        // 查询未读消息数量（私信/系统）
        int letterUnreadCount = messageService.selectLetterUnreadCount(null, userId);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(userId, null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);
        return "site/notice";
    }

    private void getMessageVo(int userId, Message message, Map<String, Object> messageVo, String topic) {
        messageVo.put("message", message);
        // 还原转义字符
        String content = HtmlUtils.htmlUnescape(message.getContent());
        Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
        messageVo.put("user", userService.getUserById((Integer) data.get("userId")));
        messageVo.put("entityType", data.get("entityType"));
        messageVo.put("entityId", data.get("entityId"));
        messageVo.put("postId", data.get("postId"));

        int count = messageService.findNoticeCount(userId, topic);
        messageVo.put("count", count);

        int unreadCount = messageService.findNoticeUnreadCount(userId, topic);
        messageVo.put("unreadCount", unreadCount);
    }

    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Model model, Page page) {
        int userId = hostHolder.getUser().getId();
        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(userId, topic));
        List<Message> noticeList = messageService.findNoticeList(userId, topic, page.getOffert(), page.getLimit());
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        if (Objects.nonNull(noticeList)) {
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                // 通知
                map.put("notice", notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userService.getUserById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                // 通知人
                map.put("fromUser", userService.getUserById(notice.getFromId()));
                noticeVoList.add(map);
            }
        }
        model.addAttribute("notices", noticeVoList);
        // 设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
        return "site/notice-detail";
    }
}
